﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using InsightAuto.Domain.Core;
using System.Web.Routing;

namespace InsightAuto.Web.Controllers
{
    public class NavigateController : Controller
    {
        private CoreContainer db = new CoreContainer();

        public PartialViewResult Brand(int id)
        {
            var par = db.Brands.SingleOrDefault(o => o.ID == id);

            string navFormat = "{首页}\\{车型大全}\\{品牌}";

            string result = BuildNavigate(navFormat, par);

            return PartialView("Navigate", result);
        }

        public PartialViewResult Series(int id)
        {
            var obj = db.Series
                .Include("Brand")
                .SingleOrDefault(o => o.ID == id);

            string navFormat = "{首页}\\{车型大全}\\{品牌}\\{车系}";

            string result = BuildNavigate(navFormat, obj, obj.Brand);

            return PartialView("Navigate", result);
        }

        private string BuildNavigate(string navFormat, params object[] pars)
        {
            var result = navFormat
                        .Replace("{首页}", GenerateLink("汽车网首页", "Index", "Home"))
                        .Replace("{车型大全}", GenerateLink("车型大全", "Index", "Car"));

            if (result.Contains("{品牌}"))
            {
                var o = pars.OfType<Brand>().SingleOrDefault();

                result = result.Replace("{品牌}", GenerateLink(o.Name, "Brand", "Car", new { id = o == null ? 0 : o.ID }));
            }

            if (result.Contains("{车系}"))
            {
                var o = pars.OfType<Series>().SingleOrDefault();

                result = result.Replace("{车系}", GenerateLink(o.Name, "Series", "Car", new { id = o == null ? 0 : o.ID }));
            }
            
            return result;
        }

        private string GenerateLink(string linkText, string actionName, string controllerName, object routeValues=null)
        {
            return HtmlHelper.GenerateLink(this.Request.RequestContext, System.Web.Routing.RouteTable.Routes,
                linkText, "Default", actionName, controllerName, routeValues == null ? null : new RouteValueDictionary(routeValues), null);
        }

    }
}
